﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using University.Workshop.Business;
using System.Collections.ObjectModel;

namespace University.Workshop.Presenters.CollectControl
{
    public class PresenterRegisterCollectControl
    {
        IRegisterCollectControlView view;

        Model.CollectControl collectControlToRegister = new Model.CollectControl();
        Model.User user = new Model.User();
        ICollection<Model.CollectControl> collectControls;

        public PresenterRegisterCollectControl(IRegisterCollectControlView view, Model.User user)
        {
            this.view = view;
            this.user.UserId = user.UserId;
        }

        public Dictionary<string, ICollection<Model.Allotment>> LlenarCbx()
        {
            Dictionary<string, ICollection<Model.Allotment>> manzanos = new Dictionary<string, ICollection<Model.Allotment>>();
            CleanSearch();

            List<Model.Square> squareList = ManagerSquare.GetSquares().ToList();

            squareList = squareList.OrderBy(x => x.SquareId).ToList();

            List<Model.Allotment> activeAllotments = ManagerAllotment.SearchActiveAllotments();

            foreach (Model.Square square in squareList)
            {
                var filteredAllotmentsBySquares = activeAllotments.FindAll(a => a.SquareId.Equals(square.SquareId));
                manzanos.Add(square.SquareId.ToString(), filteredAllotmentsBySquares);
            }

            return manzanos;
        }

        public void MostrarTotalAdeudado()
        {
            collectControls = view.CollectFinded;
            decimal total = 0;

            foreach (Model.CollectControl c in collectControls)
                total += c.PaymentAmount;

            view.TotalAmount = total;
        }

        public bool PayCollects(List<Model.CollectControl> seleccionados)
        {
            int cantidad = seleccionados.Count;
            collectControls = seleccionados;   //view.CollectsSelected;
            

            if (cantidad > 0)
            {
                try
                {
                    ManagerCollectControl.RegisterPayment(collectControls, user);

                    if (VerificarCorte())
                        ManagerCollectControl.ChangeCutSupply(collectControls);

                    return true;
                }
                catch (Exception ex)
                {
                    //Cambiar mensaje de error
                    view.NotifyErrorMessage(string.Format("Hubo un error al ingresar los datos a la base de datos.", "Registar Cobro"));
                    return false;
                }
            }
            else        //Si no selecciono ningun registro
            {
                view.NotifyErrorMessage(string.Format("Para registrar un cobro es necesario seleccionar una o más deudas pendientes.", "Registar Cobro"));
                return false;
            }
        }

        public bool SearchCollects()
        {
            bool datosCompletos = true;

            try
            {
                Model.CollectControl c = new Model.CollectControl();
                Model.Kardex k = new Model.Kardex();
                Model.Allotment a = new Model.Allotment();
                CleanSearch();

                try
                {
                    a.AllotmentName = view.Lote;
                    a.SquareId = view.Manzano;

                    a = ManagerKardex.GetAllotmentByAllotmentNameAndSquareId(a);
                    
                    if (k == null)
                        datosCompletos = false;
                    else
                    {
                        c.KardexId = a.KardexId.Value;
                        k.KardexId = c.KardexId;
                        k = ManagerKardex.GetKardexByKardexId(k);
                    }
                }
                catch (Exception ex)
                {
                    datosCompletos = false;
                }

                if (datosCompletos)
                {
                    view.CollectFinded = ManagerCollectControl.SearchByClientId(c);
                    view.NombreSocio = k.Person.Names + " " + k.Person.LastNames;
                    view.CiSocio = k.Person.PersonId;
                }
                else
                    throw new Exception("No se encontraron resultados de la busqueda...");

                MostrarTotalAdeudado();
                return true;
            }
            catch (Exception ex)
            {
                view.CollectFinded = null;
                view.NotifyErrorMessage(ex.Message);
                CleanSearch();
                return false;
            }
        }

        private void CleanSearch()
        {
            view.CollectFinded = new Collection<Model.CollectControl>();
            view.TotalAmount = 0;
        }

        public bool VerificarCorte()
        {
            bool existCutSupply;

            existCutSupply = ManagerCollectControl.CheckCutSupply(collectControls);

            return existCutSupply;
        }
    }
}
